package com.fy.module.repo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fy.common.dto.PageDto;
import com.fy.common.exception.ServiceException;
import com.fy.common.vo.PageResult;
import com.fy.common.exception.ServiceException;
import com.fy.common.vo.ApiRest;
import com.fy.module.repo.entity.Repo;
import com.fy.module.repo.mapper.RepoMapper;
import com.fy.module.repo.service.IRepoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * 题库 服务实现类
 * </p>
 *
 * @author li
 * @since 2023-03-18
 */
@Service
public class RepoServiceImpl extends ServiceImpl<RepoMapper, Repo> implements IRepoService {

    @Override
    public PageResult<Repo> findPage(PageDto<Repo> pageDto) {

        if (pageDto == null){
            throw new ServiceException("参数异常");
        }

        if (pageDto.getNow() <= 0){
            throw new ServiceException("参数异常");
        }
        //设置分页
        IPage<Repo> page = new Page<>(pageDto.getNow(),pageDto.getSize());
        //条件构造器
        QueryWrapper queryWrapper = new QueryWrapper();
        if (pageDto.getWhere().getTitle() != null){
            queryWrapper.like("title",pageDto.getWhere().getTitle());
        }

        IPage pageInfo = this.page(page,queryWrapper);

        PageResult pageResult = new PageResult();
        pageResult.setPages(pageInfo.getPages());
        pageResult.setList(pageInfo.getRecords());
        pageResult.setTotal(pageInfo.getTotal());



        return pageResult;
    }
    @Override
    @Transactional
    public ApiRest saveRepo(Repo repo) {
        if (repo == null){
            throw new ServiceException("参数异常");
        }
        if (StringUtils.isEmpty(repo.getId())){
            repo.setId(IdWorker.getIdStr());
            repo.setCreateTime(new Date());
        }
        repo.setUpdateTime(new Date());
        boolean save = this.saveOrUpdate(repo);

        return ApiRest.success();
    }
}
